const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = async(event, context) => {
    const response = {};
    const dakaType = event.type;
    const { OPENID } = cloud.getWXContext();
    if (dakaType && dakaType !== 'all') {
        const { data: dakaRecords } = await db.collection('dakaRecords')
            .where({
                openid: _.eq(OPENID),
                cardType: _.eq(dakaType),
                needScore: _.eq(true)
            })
            .get();
        const date = [];
        const data = [];
        dakaRecords.forEach(dakaRecord => {
            data.push(dakaRecord[`${dakaType}Score`]);
            date.push(dakaRecord['createdDay'])
        })
        response.code = 200;
        response.body = {
            data,
            date
        }
    } else {
        const { data: dakaRecords } = await db.collection('dakaRecords')
            .where({
                openid: _.eq(OPENID),
                needScore: _.eq(true)
            })
            .get();
        const date = [];
        const data = [];
        dakaRecords.forEach(dakaRecord => {
            if (dakaRecord.cardType !== 'all') {
                data.push(dakaRecord[`${dakaRecord.cardType}Score`]);
                date.push(dakaRecord['createdDay']);
            } else {
                data.push(dakaRecord[`totalScore`]);
                date.push(dakaRecord['createdDay']);
            }

        })
        response.code = 200;
        response.body = {
            data,
            date
        }
    }

    return response;
}